# -*- coding: UTF-8 -*-

import tensorflow as tf
import gp_db
import os
import numpy as np

db_conn = gp_db.db_con("192.168.1.116", 'postgres', '5432', 'gpadmin', 'pivotal')
test_column = "data"
test_table = "image_tests"

path = "/plpy"
print(os.path.abspath(path))


def insertTab(input_table, output_table, labels):
    create_sql = " create table %s as select * ,'' as label from %s where 1<>1 " % (output_table, input_table)
    db_conn.execute(create_sql)

    insert_sql = 'insert into %s( ' % output_table
    rs = db_conn.execute('select * from %s order by id ' % input_table)
    i = 0
    for r in rs:
        if i == 0:
            for key in r:
                insert_sql = insert_sql + key + ','
            insert_sql = insert_sql + 'label)values'
        insert_sql = insert_sql + "("
        for key in r:
            # 如果是数组类型
            if isinstance(r[key], list):
                tstr = "{" + ','.join(str(c) for c in r[key]) + "}"
                insert_sql = insert_sql + "'" + tstr + "',"
            else:
                insert_sql = insert_sql + "'" + str(r[key]) + "',"
        insert_sql = insert_sql + "'" + str(labels[i]) + "'),"
        i = i + 1
    plpy.info(insert_sql[:-1])
    plpy.execute(insert_sql[:-1])


def predict(test_data,model_name):
    with tf.Session() as sess:
      #加载模型
      saver = tf.train.import_meta_graph('/plpy/model_file/%s/tf_model.meta'%model_name)
      saver.restore(sess,"/plpy/model_file/%s/tf_model"%model_name )
      graph = tf.get_default_graph()
      prediction = graph.get_tensor_by_name("czcprediction:0")
      x = graph.get_tensor_by_name("input_image:0")
      #进行预测
      pr = sess.run(prediction, feed_dict={x: test_data})
      return pr
# 查出数据
q = "select %s from %s limit 10 " % (test_column, test_table)
rv1 = []
rv = db_conn.getCollect(q)
for i in rv :
  rv1.append(i['data'])
rv1 = np.array(rv1)
test_data = np.multiply(rv1, 1.0 / 255.0)
predict_result = predict(test_data,"model1")
print(predict_result )

